/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.buzzwords.behaviors;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author devinpartlow
 */
public class BehaviorUtils {
    
    static EntityManagerFactory emf;

    public static void setupClass() {
        emf = Persistence.createEntityManagerFactory("BuzzwordsTestPU");
    }

    public static void teardownClass() {
        emf.close();
    }

    public void persist(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
        merge(object);
    }

    public void remove(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.remove(em.merge(object));
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }

    public void merge(Object object) {
        EntityManager em = emf.createEntityManager();
        em.merge(object);
        em.close();
    }

}
